//
//  NetworkTool.m
//  AffectionBee
//
//  Created by 李通 on 16/8/18.
//  Copyright © 2016年 chivalrous. All rights reserved.
//

#import "NetworkTool.h"
#import "SVProgressHUD.h"

@implementation NetworkTool


//MYMARK: - 重设网络基本设置
+ (instancetype)sharedManager {
    
    static NetworkTool *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        //1.实例化
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        instance = [[NetworkTool alloc] initWithSessionConfiguration:config];
        
        //2.可接受格式
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
        
        //3.请求格式（默认：二进制）
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        
        //4.设置超时时间
        config.timeoutIntervalForRequest = 15;
    });
    return instance;
}


//MYARK: - 根据网络请求类型封装不同网络请求方法
- (void)oauthLoadDataWithNetworkToolType:(NetworkToolType)type UrlString:(NSString *)urlString parameters:(NSDictionary *)parameters SuccessBlock:(SuccessCompletedBlock)success failure:(FailureCompletedBlock)failure {
    
    [SVProgressHUD show];
    
    //如果请求类型为GET请求
    if (type == NetworkToolTypeGET) {
        
        [[NetworkTool sharedManager] GET:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            //如果网络请求结果不为空则回调block
            if (responseObject) {
                //回调之前取消网络请求提示
                [SVProgressHUD dismiss];
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (error) {
                //回调之前取消网络请求提示
                [SVProgressHUD dismiss];
                failure(error);
            }
        }];
        //如果不是GET请求，那么就是POST请求
    } else {
        
        [[NetworkTool sharedManager] POST:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            if (responseObject) {
                //回调之前取消网络请求提示
                [SVProgressHUD dismiss];
                success(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (error) {
                //回调之前取消网络请求提示
                [SVProgressHUD dismiss];
                failure(error);
            }
        }];
    }
}

@end
